package com.novelot.plugin.allinone;

import javax.swing.*;
import java.awt.event.*;

public class SingletonDialog extends JDialog {
    private JPanel contentPane;
    private JButton buttonOK;
    private JButton buttonCancel;
    private JTextField tfClassName;

    public SingletonDialog() {
        setContentPane(contentPane);
        setModal(true);
        getRootPane().setDefaultButton(buttonOK);


        buttonOK.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                onOK();
            }
        });

        buttonCancel.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                onCancel();
            }
        });

        // call onCancel() when cross is clicked
        setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
        addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                onCancel();
            }
        });

        // call onCancel() on ESCAPE
        contentPane.registerKeyboardAction(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                onCancel();
            }
        }, KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
    }

    private void onOK() {
        if (mListener != null) {
            String text = tfClassName.getText();
            mListener.onOK(text);
        }
        dispose();
    }

    private void onCancel() {
        if (mListener != null) {
            mListener.onCancel();
        }
        dispose();
    }

    public interface Listener {
        void onOK(String className);

        void onCancel();
    }

    private Listener mListener;

    public void setListener(Listener listener) {
        mListener = listener;
    }
}
